package com.ruoyi.common.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.business.entity.YytBaseCatalog;
import com.ruoyi.common.business.dao.YytBaseCatalogMapper;
import com.ruoyi.common.business.service.YytBaseCatalogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* <p>
    * 商品分类表 服务实现类
    * </p>
*
* @author huangshun
* @since 2021-12-16
*/
@Service
public class YytBaseCatalogServiceImpl extends ServiceImpl<YytBaseCatalogMapper, YytBaseCatalog> implements YytBaseCatalogService {
    @Autowired
    private YytBaseCatalogMapper yytBaseCatalogMapper;

    @Override
    public YytBaseCatalog selectYytBaseCatalogById(String catalogId) {
        return yytBaseCatalogMapper.selectById(catalogId);
    }

    @Override
    public List<YytBaseCatalog> geiChildNode(String catalogId) {
        return yytBaseCatalogMapper.getChildNode(catalogId);
    }

    @Override
    public List<String> getChildNodeAll(String catalogId) {
        List<String> result = new ArrayList<>();
        YytBaseCatalog baseCatalog = super.getById(catalogId);
        QueryWrapper<YytBaseCatalog> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", catalogId).eq("del_flag", 0).eq("status",0);
        List<YytBaseCatalog> list = super.list(wrapper);
        if(list.size() > 0){
            List<YytBaseCatalog> treeBaseData = getTreeBaseData(list);
            treeBaseData.addAll(0, list);
            treeBaseData.add(baseCatalog);
            for (YytBaseCatalog yb : treeBaseData){
                result.add(yb.getId());
            }
        }else{
            result.add(baseCatalog.getId());
        }

        return result;
    }

    /**
     * 抽取出来的方法
     * @return
     */
    public List<YytBaseCatalog> getTreeBaseData(List<YytBaseCatalog> list){
        List<YytBaseCatalog> result = new ArrayList<>();
        for (YytBaseCatalog yb : list){
            QueryWrapper<YytBaseCatalog> wrapper = new QueryWrapper<>();
            wrapper.eq("parent_id", yb.getId()).eq("del_flag", 0).eq("status",0);
            List<YytBaseCatalog> list1 = super.list(wrapper);
            if(list1.size() > 0){
                List<YytBaseCatalog> treeBaseData = getTreeBaseData(list1);
                list1.addAll(0, treeBaseData);
                result.addAll(0, list1);
            }
        }
        return result;
    }



}
